<style>
    #user-img img {
        width: 0px;
        /*margin: 1rem;*/
        cursor: pointer;
    }
</style>
<div class="layui-fluid layui-anim febs-anim" id="febs-batches" lay-title="鸡批次">
    <div class="layui-row layui-col-space8 febs-container">
        <div class="layui-col-md7 layui-col-sm6 layui-col-xs12">
            <div class="layui-card">
                <div class="layui-card-body febs-table-full">
                    <form class="layui-form layui-table-form" lay-filter="batches-table-form" id="batches-table-form">
                        <div class="layui-row">
                            <div class="layui-col-md9 layui-col-sm9 layui-col-xs9">
                                <div class="layui-form-item">
                                    <div class="layui-inline">
                                        <label class="layui-form-label layui-form-label-sm">日期</label>
                                        <div class="layui-input-inline">
                                            <input type="text" name="date" id="febs-batches-date" lay-verify="date"
                                                   placeholder="日期" autocomplete="off" class="layui-input">
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div class="layui-col-md3 layui-col-sm12 layui-col-xs12 table-action-area">
                                <div class="layui-btn layui-btn-sm layui-btn-primary table-action" id="query">
                                    <i class="layui-icon">&#xe848;</i>
                                </div>
                                <div class="layui-btn layui-btn-sm layui-btn-primary table-action" id="reset">
                                    <i class="layui-icon">&#xe79b;</i>
                                </div>
                                <div class="layui-btn layui-btn-sm layui-btn-primary table-action action-more"
                                     shiro:hasAnyPermissions="batches:add,batches:delete,batches:export">
                                    <i class="layui-icon">&#xe875;</i>
                                </div>
                            </div>
                        </div>
                    </form>
                    <table lay-filter="batchesTable" lay-data="{id: 'batchesTable'}"></table>
                </div>
            </div>
        </div>
        <div class="layui-col-md5 layui-col-sm6 layui-col-xs12" shiro:hasPermission="batches:add">
            <div class="layui-card">
                <div class="layui-card-header" id="form-header">新增批次</div>
                <div class="layui-card-body febs-table-full">
                    <form class="layui-form layui-table-form" action="" lay-filter="batches-form">
                        <div class="layui-form-item febs-hide">
                            <label class="layui-form-label febs-form-item-require">批次ID：</label>
                            <div class="layui-input-block">
                                <input type="text" name="batchesId" class="layui-input">
                            </div>
                        </div>
                        <div class="layui-form-item">
                            <label class="layui-form-label febs-form-item-require">数量：</label>
                            <div class="layui-input-block">
                                <input type="text" name="number" autocomplete="off" class="layui-input" minlength="1"
                                       lay-verify="range|number">
                            </div>
                        </div>
                        <div class="layui-form-item">
                            <label class="layui-form-label febs-form-item-require">出生地址：</label>
                            <div class="layui-input-block">
                                <input type="text" name="address" autocomplete="off" class="layui-input" minlength="2"
                                       lay-verify="range">
                            </div>
                        </div>
                        <div class="layui-form-item">
                            <label class="layui-form-label layui-form-label-sm">种类:</label>
                            <div class="layui-input-block">
                                <select name="type" lay-filter="type" id="type">
                                </select>
                            </div>
                        </div>
                        <div class="layui-form-item">
                            <label class="layui-form-label">出生日期：</label>
                            <div class="layui-input-block">
                                <input type="text" name="birthday" id="birthday"
                                       placeholder="出生日期" autocomplete="off" class="layui-input">
                            </div>
                        </div>
                        <div class="layui-form-item">
                            <label class="layui-form-label">上环日期：</label>
                            <div class="layui-input-block">
                                <input type="text" name="markDate" id="markDate"
                                       placeholder="上环日期" autocomplete="off" class="layui-input">
                            </div>
                        </div>
                        <div class="layui-form-item">
                            <label class="layui-form-label">检疫日期：</label>
                            <div class="layui-input-block">
                                <input type="text" name="credentialDate" id="credentialDate"
                                       placeholder="检疫日期" autocomplete="off" class="layui-input">
                            </div>
                        </div>
                        <div class="layui-form-item">
                            <label class="layui-form-label">证书：</label>
                            <div class="layui-input-block">
                                <div class="layui-upload">
                                    <button type="button" class="layui-btn" id="file">上传图片</button>
                                </div>
                            </div>
                        </div>
                        <div id="user-img">
                            <img alt="头像" title="点我更换头像" data-th-src="@{febs/images/avatar/empty.jpg}">
                        </div>
                        <div class="layui-form-item febs-hide">
                            <button type="reset" class="layui-btn" id="reset-form"></button>
                            <button class="layui-btn" lay-submit="" lay-filter="batches-form-submit"
                                    id="submit-form"></button>
                        </div>
                    </form>
                </div>
                <div class="layui-card-footer">
                    <button class="layui-btn" id="submit">保存</button>
                </div>
            </div>
        </div>
    </div>
</div>
<script type="text/html" id="batches-option">
    <span shiro:lacksPermission="batches:update,batches:delete">
        <span class="layui-badge-dot febs-bg-orange"></span> 无权限
    </span>
    <a lay-event="detail" shiro:hasPermission="batches:update"><i
            class="layui-icon febs-edit-area febs-green">&#xe7a5;</i></a>
    <a lay-event="edit" shiro:hasPermission="batches:update"><i class="layui-icon febs-edit-area febs-blue">&#xe7a4;</i></a>
    <a lay-event="del" shiro:hasPermission="batches:delete"><i
            class="layui-icon febs-edit-area febs-red">&#xe7f9;</i></a>
</script>
<script data-th-inline="none" type="text/javascript">
    layui.use(['dropdown', 'jquery', 'laydate', 'febs', 'form', 'eleTree', 'table', 'validate', 'upload', 'treeSelect'], function () {
        var $ = layui.jquery,
            upload = layui.upload,
            laydate = layui.laydate,
            febs = layui.febs,
            form = layui.form,
            table = layui.table,
            treeSelect = layui.treeSelect,
            eleTree = layui.eleTree,
            dropdown = layui.dropdown,
            validate = layui.validate,
            $view = $('#febs-batches'),
            $query = $view.find('#query'),
            $reset = $view.find('#reset'),
            $submit = $view.find('#submit'),
            $searchForm = $view.find('#batches-table-form'),
            $header = $view.find('#form-header'),
            tableIns;

        form.verify(validate);
        form.render();
        //检疫证书
        var fileUri = null;
        initTable();
        //普通图片上传
        var uploadInst = upload.render({
            elem: '#file'
            , url: ctx + "uploadFile"
            , before: function (obj) {
                //预读本地文件示例，不支持ie8
                obj.preview(function (index, file, result) {
                    $view.find('#user-img img').attr('src', result);//图片链接（base64）
                    $view.find('#user-img img')[0].style.width = "100%";
                });
            }
            , done: function (res) {
                //上传成功
                if (res.code == 200) {
                    febs.alert.success('上传图片成功！');
                    fileUri = res.data.fileDownloadUri;
                }
            }
            , error: function () {
                febs.alert.error('上传图片失败！');
            }
        });
        laydate.render({
            elem: '#markDate'
        });
        laydate.render({
            elem: '#credentialDate'
        });
        laydate.render({
            elem: '#febs-batches-date'
        });
        laydate.render({
            elem: '#birthday'
            // range: true
        });

        $.get("chicken/typeList", function (result) {
            result.data.forEach(type => {
                let option = "<option value='" + type.id + "'>" + type.type_name + "</option>";
                $("#type").append(option);
            })
            form.render()
        })

        dropdown.render({
            elem: $view.find('.action-more'),
            click: function (name, elem, event) {
                var checkStatus = table.checkStatus('batchesTable');
                if (name === 'add') {
                    resetRoleForm();
                }
                if (name === 'delete') {
                    if (!checkStatus.data.length) {
                        febs.alert.warn('请选择需要删除的批次');
                    } else {
                        febs.modal.confirm('删除批次', '确定删除所选批次？', function () {
                            var batchesIds = [];
                            layui.each(checkStatus.data, function (key, item) {
                                batchesIds.push(item.batchesId);
                            });
                            deleteRoles(batchesIds.join(','));
                        });
                    }
                }
                if (name === 'export') {
                    var params = getQueryParams();
                    params.pageSize = $view.find(".layui-laypage-limits option:selected").val();
                    params.pageNum = $view.find(".layui-laypage-em").next().html();
                    febs.download(ctx + 'batches/excel', params, '鸡批次表.xlsx');
                }
            },
            options: [{
                name: 'add',
                title: '新增批次',
                perms: 'batches:add'
            }, {
                name: 'delete',
                title: '删除批次',
                perms: 'batches:delete'
            }, {
                name: 'export',
                title: '导出Excel',
                perms: 'batches:export'
            }]
        });

        table.on('tool(batchesTable)', function (obj) {
            var data = obj.data,
                layEvent = obj.event;
            if (layEvent === 'detail') {
                $header.text('修改批次');
                form.val("batches-form", {
                    "batchesId": data.batchesId,
                    "address": data.address,
                    "type": data.type,
                    "birthday": data.birthday,
                    "markDate": data.markDate,
                    "credentialDate": data.credentialDate,
                    "number": data.number,
                    "fileUri": data.file
                });
                if (data.file != '' && data.file != null) {
                    $view.find('#user-img img').attr('src', data.file);
                    $view.find('#user-img img')[0].style.width = "100%";
                } else {
                    $view.find('#user-img img')[0].style.width = "0rem";
                }
            }
            if (layEvent === 'del') {
                febs.modal.confirm('删除批次', '确定删除该批次？', function () {
                    deleteRoles(data.batchesId);
                });
            }
            if (layEvent === 'edit') {
                febs.modal.open('修改鸡信息', 'pedometer/chicken/' + data.batchesId, {
                    area: $(window).width() <= 750 ? '90%' : '50%',
                    btn: ['关闭'],
                    btn2: function () {
                        layer.closeAll();
                    }
                });
            }
        });

        $query.on('click', function () {
            resetRoleForm();
            tableIns.reload({where: getQueryParams(), page: {curr: 1}});
        });

        $reset.on('click', function () {
            resetRoleForm();
            $searchForm[0].reset();
            tableIns.reload({where: getQueryParams(), page: {curr: 1}});
        });

        $submit.on('click', function () {
            $view.find('#submit-form').trigger('click');
        });

        function initTable() {
            tableIns = febs.table.init({
                elem: $view.find('table'),
                id: 'batchesTable',
                url: ctx + 'batches/list',
                cols: [[
                    {type: 'checkbox'},
                    {field: 'typeName', title: '品种'},
                    {field: 'number', title: '数量'},
                    {field: 'birthday', title: '出生日期'},
                    {field: 'markDate', title: '上环日期'},
                    {title: '操作', toolbar: '#batches-option', width: 140}
                ]]
            });
        }

        function getQueryParams() {
            return {
                // roleName: $searchForm.find('input[name="roleName"]').val().trim(),
                invalidate_ie_cache: new Date()
            };
        }

        function resetRoleForm() {
            $view.find('#reset-form').trigger('click');
            $view.find('#user-img img')[0].style.width = "0rem";
            $header.text('新增批次');
        }

        form.on('submit(batches-form-submit)', function (data) {
            data.field.file = fileUri;
            data.field.typeName = $("#type  option:selected").html();
            addOrUpdateRole(data.field);
            return false;
        });

        function deleteRoles(batchesId) {
            febs.get(ctx + 'batches/delete/' + batchesId, null, function () {
                febs.alert.success('删除角色批次成功');
                $query.trigger('click');
            })
        }

        var addOrUpdateRole = function (data) {
            if (data.batchesId && $header.text() === '修改批次') {
                console.log(fileUri)
                febs.post(ctx + 'batches/update', data, function () {
                    febs.alert.success('修改批次成功');
                    $query.trigger('click');
                    fileUri = null;
                });
            } else {
                febs.post(ctx + 'batches', data, function () {
                    febs.alert.success('新增批次成功');
                    $query.trigger('click');
                    fileUri = null;
                });
            }
        }
    });
</script>